var dao = require('./mysql-dao.js');

var count = 0;

var createRoom = function() {
	// TODO: return random number
	return count++;
};

/*
 * Export functions
 */
exports.initialize = function(io, socket) {
	console.log('initialize messenger module...');
	
	socket.on('login', function(data) {
		var username = data.username;
		var password = data.password;
		
		console.log('check user credential...');
		
		dao.login(username, password, function(result) {
			// return login result as boolean type
			socket.emit('login', result);
			
			if (result) {
				// create user room to make it easier to find user's socket
				socket.join(username);
				socket.set('name', username);
			}
		});
	});
	
	socket.on('buddies', function() {
		socket.get('name', function(error, name) {
			console.log('get buddies of ' + name + '...');
			dao.getBuddies(name, function(rows) {
				console.log(rows);
				socket.emit('buddies', rows);
			});
		});
	});
	
	socket.on('chat', function(to) {
		var room = createRoom();
		socket.join(room);
		
		// TODO: consider to add timer to make user leave the room after specific time period.
		
		// send 'to user a message to get permission
		socket.get('name', function(error, name) {
			console.log(name + ' requested chatting with ' + to + ' in room ' + room);
			io.sockets['in'](to).emit('join', {
				from: name,
				room: room
			});	
		});
	});
	
	socket.on('join', function(room) {
		console.log('user joined room ' + room);
		socket.join(room);
		
		// notify that all users have joined the room
		io.sockets['in'](room).emit('start', room);
	});
	
	socket.on('message', function(data) {
		console.log('message arrived: ' + data.message);
		
		socket.get('name', function(error, name) {
			io.sockets['in'](data.room).emit('message', {
				from: name,
				message: data.message
			});
		});
	});
	
	socket.on('leave', function(room) {
		console.log('user leaves the room ' + room);
		socket.leave('/' + room);
		
		socket.get('name', function(error, name) {
			io.sockets['in'](room).emit('leave', name);
		});		
	});
};

